package cn.topevery.garden.entity.bo;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author LiuHui
 * @description: TODO
 * @date 2024-01-10
 */
@Data
@Component
@ConfigurationProperties(prefix = "hw.config.captcha")
public class CaptchaCacheBO {
    /** 验证码 **/
    private String captcha;
    /** 会话时间 **/
    private LocalDateTime sessionTime;
    /** 验证码有效期至 **/
    private LocalDateTime captchaExpireAt;

    /** 验证码有效期（秒） **/
    public static long EXPIRE = 60;
    /** 验证码前缀 **/
    public static String PREFIX = "CAPTCHA_";

    public CaptchaCacheBO() {
    }

    public CaptchaCacheBO(String captcha) {
        this(captcha, EXPIRE);
    }

    @Value("${expire:60}")
    public void setExpire(int expire) {
        CaptchaCacheBO.EXPIRE = expire;
    }

    public CaptchaCacheBO(String captcha, long expire) {
        this(captcha, LocalDateTime.now(), expire);
    }

    public CaptchaCacheBO(String captcha, LocalDateTime sessionTime) {
        this(captcha, sessionTime, EXPIRE);
    }

    public CaptchaCacheBO(String captcha, LocalDateTime sessionTime, long expire) {
        this.captcha = captcha;
        this.sessionTime = sessionTime;
        this.captchaExpireAt = sessionTime.plusSeconds(0 >= expire ? EXPIRE : expire);
    }

    public boolean isExpired(LocalDateTime time) {
        return time.isAfter(this.captchaExpireAt);
    }
}
